<template>
    <div v-on:paste="handlePaste" class="parseImg">
        <a-space direction="vertical" fill>

        <div v-if="pastedFile">
            <div>粘贴的截图（黑色三角为采样点）：</div>
            <img :src="pasteImg" style="max-width: 100%;max-height: 300px;"/>
        </div>
        <div class="hint" v-else>
            使用截图截下要提取的Colobar(不要留有边缘)<br/>
            然后在此按下 Ctrl+V / Command+V 粘贴图片
        </div>

        <div style="display: flex;align-items:center;">
            <div>采样数：</div>
            <a-input-number v-model="sampleNumber" :min="2" mode="button" style="width: 120px;" @change="resample"/>
            <div style="flex-grow: 1;"/>
            <div>前偏移：</div>
            <a-input-number v-model="foreOffset" :min="1" mode="button" style="width: 120px;" @change="resample"/>
            <div style="flex-grow: 1;"/>
            <div>后偏移：</div>
            <a-input-number v-model="backOffset" :min="1" mode="button" style="width: 120px;" @change="resample"/>

            <div style="flex-grow: 1;"/>
            <a-checkbox v-model="reverse" @change="resample" >反转顺序</a-checkbox>

        </div>

        <template v-if="result.length>2">
            <a-divider />
            <div>识别结果:</div>
            <div class="previewBox" :style="{background: previewColor}"></div>
            <div style="display: flex;gap:3rem">
                <a-button @click="result=[]" type="secondary" >重置</a-button>
                <a-button type="primary" @click="useResult" long >使用识别结果</a-button>
            </div>
        </template>
        </a-space>
    </div>
</template>

<script setup lang="ts">
import { Notification } from '@arco-design/web-vue';
import { rgb2hex } from '../api';
import { computed, ref } from 'vue';

const sampleNumber = ref(5);

const result = ref<string[]>([]);

const pastedFile = ref<File | null>(null);
const foreOffset = ref(1);
const backOffset = ref(1);

const pasteImg = ref<string>('');
const reverse = ref(false);

const previewColor = computed(() => {
    if (result.value.length < 2) {
        return 'none';
    }
    return `linear-gradient(to right, ${result.value.join(",")})`;
});

const handlePaste = (event: ClipboardEvent) => {
    const items = (event.clipboardData || window.clipboardData).items;
    let file = null;

    if (!items || items.length === 0) {
        Notification.warning("当前浏览器不支持粘贴图片");
        return;
    }
    // 搜索剪切板items
    for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") !== -1) {
            file = items[i].getAsFile();
            break;
        }
    }
    if (!file) {
        Notification.error("粘贴内容非图片");
        return;
    }
    parse(file);

}

const exportPasteImg = (file: File) =>{
    const reader = new FileReader();
    reader.readAsDataURL(file);
    pastedFile.value = file;

    // 读取图片长宽
    reader.onload = function (e) {
        const img = new Image();
        img.src = e.target?.result as string;
        img.onload = function () {
            const imgIsHorizontal = img.width > img.height;
            // 根据采样数，采样图片的颜色
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d');
            canvas.width = imgIsHorizontal ? img.width : 1;
            canvas.height = imgIsHorizontal ? 1 : img.height;
            ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);
            
            const data = ctx?.getImageData(0, 0, canvas.width, canvas.height).data;

            canvas = document.createElement('canvas');
            ctx = canvas.getContext('2d');
            canvas.width = imgIsHorizontal ? img.width : img.height;
            canvas.height = 70;
            const imgHeight = 50;
            // 将data拉伸绘制到新的canvas上

            // 画上采样点
            const len = (imgIsHorizontal ? img.width : img.height) - foreOffset.value - backOffset.value;
            const ctx2 = canvas.getContext('2d');
            for (let i = 0; i < sampleNumber.value; i++) {
                const loc = foreOffset.value + Math.floor(len * i / (sampleNumber.value - 1));
                if (ctx2) {
                    ctx2.beginPath();
                    ctx2.moveTo(loc, 55);
                    ctx2.lineTo(loc - 3, 65);
                    ctx2.lineTo(loc + 3, 65);
                    ctx2.closePath();
                    ctx2.fillStyle = 'black';
                    ctx2.fill();
                }
            }


            if(imgIsHorizontal){
                ctx?.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, imgHeight);
            }else{
                ctx?.rotate(Math.PI/2);
                ctx?.drawImage(img, 0, 0, img.width, img.height, 0, -canvas.width, imgHeight, canvas.width);
            }


            pasteImg.value = canvas.toDataURL();
        }
    }

}

const parse = (file: File)=>{
    const reader = new FileReader();
    reader.readAsDataURL(file);
    pastedFile.value = file;
    exportPasteImg(file);

    // 读取图片长宽
    reader.onload = function (e) {
        const img = new Image();
        img.src = e.target?.result as string;
        img.onload = function () {
            const imgIsHorizontal = img.width > img.height;
            // 根据采样数，采样图片的颜色
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = imgIsHorizontal ? img.width : 1;
            canvas.height = imgIsHorizontal ? 1 : img.height;
            ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);

            const imgData = ctx?.getImageData(0, 0, canvas.width, canvas.height).data;

            const colormap: string[] = [];
            const len = (imgIsHorizontal ? canvas.width : canvas.height ) - foreOffset.value - backOffset.value;
            for (let i = 0; i < sampleNumber.value; i++) {
                const loc = foreOffset.value + Math.floor(len * i / (sampleNumber.value - 1));
                const r = imgData![loc * 4];
                const g = imgData![loc * 4 + 1];
                const b = imgData![loc * 4 + 2];
                const a = imgData![loc * 4 + 3];
                const color = rgb2hex(r, g, b);
                colormap.push(color);
            }
            if(reverse.value){
                colormap.reverse();
            }

            result.value = colormap;
        };
    };
}

const resample = ()=>{
    if(pastedFile.value){
        parse(pastedFile.value);
    }
}

const emit = defineEmits(['use']);
const useResult = ()=>{
    emit('use', result.value);
}


</script>

<style scoped>
.previewBox{
    width: 100%;
    height: 50px;

}
.hint{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid var(--color-border-2);
    padding: 2rem 0;
}
</style>